//
//  JMDisplayKeyViewController.m
//  OpenSesame
//
//  Created by zhangjiaming on 15/12/25.
//  Copyright © 2015年 OpenSesame. All rights reserved.
//

#import "JMDisplayKeyViewController.h"
#import "JMCarKeyCell.h"
#import "JMKeyInforController.h"
#import "JMDisplayFrame.h"

@interface JMDisplayKeyViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) UITableView *tableView;

/** 存放每个JMCarKeyCell的内容与大小 */
@property (strong, nonatomic) NSArray *displayFrames;
@end

@implementation JMDisplayKeyViewController

- (NSArray *)displayFrames {
    if (!_displayFrames) {
        NSMutableArray *arr = [NSMutableArray array];
        for (JMCar *car in self.cars) {
            JMDisplayFrame *displayFrame = [[JMDisplayFrame alloc] init];
            displayFrame.car = car;
            [arr addObject:displayFrame];
        }
        _displayFrames = arr;
    }
    return _displayFrames;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = JMColor(242, 242, 242);
    // 设置界面
    [self setUpInterface];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  设置界面
 */
- (void)setUpInterface {
    // 设置tableView
    UITableView *tableView = [[UITableView alloc] init];
    self.tableView = tableView;
    [self.view addSubview:tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.width = JMPhoneWidth;
    tableView.height = JMPhoneHeight;
    tableView.x = 0;
    tableView.y = 7; // 预留高度为7的灰色；
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 去掉多余的cell
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    tableView.tableFooterView = view;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.displayFrames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建cell
    JMCarKeyCell *cell = [JMCarKeyCell cellWithTableView:tableView];
    
    // 传递视图模型
    cell.displayFrame = self.displayFrames[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 取出这行对应的frame模型
    JMDisplayFrame *displayFrame = self.displayFrames[indexPath.row];
    return displayFrame.cellHeight;
}

/**
 *  选择cell.跳转钥匙信息控制器
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 返回时cell没有了背景颜色
    [tableView reloadData];
    JMKeyInforController *keyInforVC = [[JMKeyInforController alloc] init];
    JMCar *car = self.cars[indexPath.row];
    keyInforVC.title = car.name;
    [self.navigationController pushViewController:keyInforVC animated:YES];
}

@end
